package com.liuguangzhou.shiro;

import com.liuguangzhou.domain.User;
import com.liuguangzhou.service.UserService;
import com.liuguangzhou.service.impl.UserServiceImpl;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserRealm
 * @Description: TODO
 * @Author liuguangzhou
 * @Date 2020/3/9
 * @Version V1.0
 **/
//继承AuthorizingRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    /**
     * 执行授权逻辑
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权逻辑");

        //给资源进行授权
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
//        List list=new ArrayList();
//        list.add("add");
//        list.add("admin");

        //添加资源的授权字符串

        Subject subject=SecurityUtils.getSubject();
        User user=(User) subject.getPrincipal();  //getPrincipal 得到的是 doGetAuthenticationInfo SimpleAuthenticationInfo的第一个参数
        User dbUser=userService.findByid(user.getId());
        info.addStringPermission(dbUser.getPerms());
        return info;
    }


    /**
     * 执行认证逻辑
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行授权逻辑");

        //假设数据库的用户名和密码
//        String name = "samuel";
//        String password = "123456";


        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;

        User user=userService.findByname(token.getUsername());
        if (user==null){
            //用户名不存在
            return null;//shiro底层会抛出UnKnowAccountException
        }


        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
